﻿using SHDocVw;
using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    /// <summary>
    /// 对于打开网页的超时错误处理暂时都没有做，之后在完善
    /// </summary>
    public class OpenWebPageNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            OpenWebPageNParam? param = item.ControlParam as OpenWebPageNParam;
            string appPath = param.BrowserPath;
            this.GetStringVar(ref appPath, globleData);
            BrowserType browserType = param.BrowType;
            string expireTimeString = param.LoadExpireTime;
            this.GetStringVar(ref expireTimeString, globleData);
            int expiretime = int.Parse(expireTimeString);
            int expireDealType = param.ExpireDealType;
            string url = param.Url;
            this.GetStringVar(ref url, globleData);
            string saveVarName = param.OutVarName;
            this.GetStringVar(ref saveVarName, globleData);
            BrowserUtil browserUtil;
            switch (browserType) { 
                case BrowserType.GOOGLE:
                    browserUtil = new ChromeUtil();
                    WebPage webPage = browserUtil.OpenUrl(url, expiretime, appPath) as WebPage;
                    if(webPage == null){
                        throw new RpaRuntimeException($"打开网页失败{url}");
                    }
                    webPage.VarName = saveVarName;
                    this.saveVar(globleData, saveVarName, webPage, DefaultContents.RUNNING_PARAM);
                    break;
                case BrowserType.IE:
                    browserUtil = new IEUtil();
                    InternetExplorer ie = browserUtil.OpenUrl(url, expiretime) as InternetExplorer;
                    break;
                case BrowserType.EDGE:
                    browserUtil = new EdgeUtil();
                    browserUtil.OpenUrl(url, expiretime, appPath);
                    break;
                default:
                    throw new RpaRuntimeException("浏览器类型错误");
            }
            return currentIndex;
        }
    }
}
